package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.atmilan.quartz.model.entity.Discount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.StoreProductNorm;
import com.atmilan.quartz.model.entity.pure.PureImages;
import com.atmilan.quartz.model.entity.pure.PureProduct;
import com.atmilan.quartz.model.entity.pure.PureProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.IStoreProductNormService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourcePureProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    IStoreProductNormService storeProductNormService;

    /**
     *
     * 构建DO对象（pure）
     * @param product
     * @param skus
     * @return
     */
    public StoreProductCrmebRequest buildPureProduct(PureProduct product, List<PureProductSku> skus,Map<String, PureImages> imagesMap,List<Discount> discountList) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            String image = null;
            String images = null;
            //处理颜色
            List<PureImages> pureImagesList = skus.stream().map(e -> imagesMap.get(e.getEan13())).collect(Collectors.toList());
            pureImagesList.removeAll(Collections.singleton(null));
            Set<String> set = new HashSet<>();
            if(CollectionUtils.isNotEmpty(pureImagesList)){
                for (PureImages pureImages : pureImagesList) {
                    set.addAll(JSONArray.parseArray(pureImages.getImages(), String.class));
                }
            }
            else {
                PureImages pureImages = imagesMap.get(product.getEan13());
                List<PureImages> collect = new ArrayList<>();
                if(pureImages != null){
                    collect = imagesMap.values().stream().filter(e -> e.getProductId().equals(pureImages.getProductId())).collect(Collectors.toList());
                    if(collect.size() == 1){
                        set.addAll(JSONArray.parseArray(pureImages.getImages(), String.class));
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(set)){
                List<String> list = new ArrayList<>(set);
                image = list.get(0);
                JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(list));
                images = gallery.toJSONString();
            }else {
                // 查询标准商品
                if(StringUtils.isBlank(product.getCodiceArticolo()) || StringUtils.isBlank(product.getFamiglia())){
                    return productRequest;
                }
                //处理国际编码
                String keyword ;
                if(product.getFamiglia().equals("PALM ANGELS") && product.getCodiceArticolo().contains("PANG")){
                    keyword  = product.getCodiceArticolo().substring(4);
                }else if(product.getFamiglia().equals("OFF WHTE") && product.getCodiceArticolo().contains("OW")){
                    keyword  = product.getCodiceArticolo().substring(2);
                }else if(product.getFamiglia().equals("FRONT STREET 8") && product.getCodiceArticolo().contains("FS8")){
                    keyword  = product.getCodiceArticolo().substring(3);
                }else {
                    int l = Math.min(product.getCodiceArticolo().length(), product.getFamiglia().length());
                    int i = 0;
                    while(i < l){
                        if(!Objects.equals(product.getCodiceArticolo().toUpperCase().charAt(i),product.getFamiglia().toUpperCase().charAt(i))){
                            break;
                        }
                        i++;
                    }
                    if(i>product.getCodiceArticolo().length()){
                        return productRequest;
                    }
                    keyword  = product.getCodiceArticolo().substring(i);
                }
                if(StringUtils.isBlank(keyword)){
                    return productRequest;
                }
                keyword = keyword.replaceAll(" ", "").replaceAll("\\\\", "").replaceAll("-", "").replaceAll("_", "").toUpperCase();
                StoreProductNorm normProduct = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
                        .eq(StoreProductNorm :: getKeyword, keyword)
                        .eq(StoreProductNorm::getColorCode,skus.get(0).getColor())
                        .last("LIMIT 1"));
//                if(normProduct == null){
//                    normProduct = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
//                            .eq(StoreProductNorm :: getKeyword, keyword)
//                            .last("LIMIT 1"));
//                }
                if(normProduct == null && product.getFamiglia().equals("PALM ANGELS")){
                    normProduct = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
                            .eq(StoreProductNorm :: getKeyword, keyword+"1")
                            .eq(StoreProductNorm::getColorCode,skus.get(0).getColor())
                            .last("LIMIT 1"));
//                    if(normProduct == null){
//                        normProduct = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
//                                .eq(StoreProductNorm :: getKeyword, keyword+"1")
//                                .last("LIMIT 1"));
//                    }
                }
                if(normProduct == null){
                    return productRequest;
                }
                image = normProduct.getImage();
                images = normProduct.getSliderImage();
            }
            //计算折扣
            BigDecimal discount = BigDecimal.ZERO;
            //分类
            List<Discount> seasonList = discountList.stream().filter(e -> product.getLinea().toUpperCase().contains(e.getSeason().toUpperCase())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(seasonList)){
                List<Discount> brandList = seasonList.stream().filter(e->StringUtils.isNotBlank(e.getBrand())).filter(e -> product.getFamiglia().toUpperCase().equals(e.getBrand().toUpperCase())).collect(Collectors.toList());
                if(CollectionUtils.isEmpty(brandList)){
                    brandList = seasonList.stream().filter(e->StringUtils.isBlank(e.getBrand())).collect(Collectors.toList());
                }
                if(CollectionUtils.isNotEmpty(brandList)){
                    List<Discount> cateList = brandList.stream().filter(e->StringUtils.isNotBlank(e.getCate())).filter(e -> product.getClasse().toUpperCase().equals(e.getCate().toUpperCase())).collect(Collectors.toList());
                    if(CollectionUtils.isEmpty(cateList)){
                        cateList = brandList.stream().filter(e->StringUtils.isBlank(e.getCate())).collect(Collectors.toList());
                    }
                    if(CollectionUtils.isNotEmpty(cateList) && cateList.size() == 1){
                        discount = cateList.get(0).getDiscount();
                    }
                }
            }
            discount = new BigDecimal(100).subtract(discount).movePointLeft(2);

            BigDecimal otPrice = skus.stream().filter(e-> StringUtils.isNotBlank(e.getPrice())).map(PureProductSku::getPrice).map(BigDecimal::new).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            PriceResult priceResult = priceUtil.eur2Rmb(skus.stream().map(PureProductSku::getPriceExVat).map(BigDecimal::new).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
            BigDecimal price = priceResult.getPrice().multiply(discount).setScale(2,BigDecimal.ROUND_UP);
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getFamiglia())
                    .eq(StoreBrand :: getType, ProductTypeEnum.PURE)
                    .last("LIMIT 1")
            );
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getFamiglia(),ProductTypeEnum.PURE);
            StoreBrand storeBrand = (null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) ? storeBrandService.getById(buyerStoreBrand.getSuperId()) : storeBrandService.getById(5429);
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.PURE.getCode() + product.getProductId()+"-"+skus.get(0).getColor();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            String color = "";
            for(PureProductSku sku : skus) {
            	color = sku.getColor();
                // 成本价
                BigDecimal erpPrice =new BigDecimal(sku.getPrice());
                // 售价
                BigDecimal adjustPrice = priceUtil.eur2Rmb(new BigDecimal(sku.getPriceExVat())).getPrice().multiply(discount).setScale(2,BigDecimal.ROUND_UP);
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getSkuId());
                storeProductAttrValue.setStock(Integer.parseInt(sku.getQuantity()));
                storeProductAttrValue.setPrice(adjustPrice);
                storeProductAttrValue.setImage(image);
                storeProductAttrValue.setCost(adjustPrice);
                storeProductAttrValue.setSourceCost(adjustPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(erpPrice);
                //发货地（欧洲）
                storeProductAttrValue.setTempId(StockAreaTempEnum.EUR.getTempId());
                List<String> suk = new ArrayList<>();
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getSize())) {
//                    String size = StringUtils.isBlank(sku.getColor()) ? sku.getSize() : sku.getColor()+"-"+sku.getSize();
                    String size = sku.getSize();
                    linkedMap.put("尺寸", size);
                    if(!sizeValueList.contains(size)){
                        sizeValueList.add(size);
                    }
                    suk.add(size);
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.PURE.getMerchantId());
            productRequest.setContent(product.getDescrizione());
            // 国际公码
            productRequest.setKeyword(product.getCodiceArticolo());
            productRequest.setStoreInfo(product.getDescrizione());
            productRequest.setStoreName(product.getClasse());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(3);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.PURE.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.PURE.getCode())
                    .eq(CategoryMatch::getOthCategoryId, product.getStat1())
                    .eq(CategoryMatch::getOthCategoryName, product.getDescrizione())
                    .last("LIMIT 1")
            );
            categoryMatchService.unMatchCategory(categoryMatch,product.getStat1(),product.getDescrizione(),null,CategoryTypeEnum.PURE);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setColorCode(skus.get(0).getColor());
//            productRequest.setSeasonCode(product.getSeasonCode());
            productRequest.setImage(image);
            productRequest.setSliderImage(images);
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.PURE.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setColorCode(color);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }
    
}
